﻿using System.IO.Ports;
using System.Text;

namespace SerialPortReceiveDemo
{
    internal class Program
    {
        private static SerialPort serialPort = new SerialPort("COM20", 9600);
        static void Main(string[] args)
        {
            serialPort.WriteBufferSize = 100;
            serialPort.ReadBufferSize = 100;
            serialPort.DataReceived += SerialPort_DataReceived;
            try
            {
                serialPort.Open();
                Console.WriteLine("串口已打开。");
                Console.WriteLine("按任意键停止接收......");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine("错误: " + ex.Message);
            }
            finally
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                    serialPort.Dispose();
                    Console.WriteLine("串口已关闭。");
                }
            }
        }

        private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //example 1
            byte[] buffer = new byte[serialPort.BytesToRead];
            int count = serialPort.Read(buffer, 0, serialPort.BytesToRead);
            string data = Encoding.UTF8.GetString(buffer);
            Console.WriteLine($"接收到的数据: {count:D4} \n" + data);

            //example 2：会导致读取数据丢失
            //string data = serialPort.ReadLine();
            //Console.WriteLine($"接收到的数据: " + data);
        }
    }
}
